package com.kgcx.organization.rabbitmq.producer;

import com.alibaba.fastjson.JSONObject;
import com.kgcx.common.rabbitmq.bean.Message;
import com.kgcx.common.rabbitmq.consts.ExchangeConst;
import com.kgcx.common.rabbitmq.consts.RoutingKeyConst;
import com.kgcx.core.utils.JsonUtil;
import com.kgcx.dbutils.service.DictService;
import com.kgcx.organization.domain.Auto;
import com.kgcx.organization.service.AutoBrandService;
import com.kgcx.organization.service.AutoModelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author 吴刚林
 * @date 2017/11/20
 */
@Slf4j
@Component
public class AutoProducer {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private DictService dictService;

    @Autowired
    private AutoBrandService autoBrandService;

    @Autowired
    private AutoModelService autoModelService;

    private static final String TYPE = "baseInfoVehicle";

    @Async
    public void addAuto(Auto auto) {
        log.info(String.format("新增车辆记录新增成功的MQ消息，车辆id[%s]。", auto.getKid()));
        bulidBrandNameAndModelName(auto);
        Message msg = Message.buildMessage(TYPE, Message.FLAG_ADD, dictService.buildDictValue(auto));
        rabbitTemplate.convertAndSend(ExchangeConst.OPC, RoutingKeyConst.OPC_COMMON,
                JSONObject.toJSONString(msg));
    }

    @Async
    public void updateAuto(Auto auto) {
        log.info(String.format("修改车辆记录新增成功的MQ消息，车辆id[%s]。", auto.getKid()));
        bulidBrandNameAndModelName(auto);
        Message msg = Message.buildMessage(TYPE, Message.FLAG_UPDATE, dictService.buildDictValue(auto));
        rabbitTemplate.convertAndSend(ExchangeConst.OPC, RoutingKeyConst.OPC_COMMON,
                JsonUtil.toString(msg));
    }

    @Async
    public void deleteAuto(Auto auto) {
        log.info(String.format("修改车辆记录新增成功的MQ消息，车辆id[%s]。", auto.getKid()));
        bulidBrandNameAndModelName(auto);
        Message msg = Message.buildMessage(TYPE, Message.FLAG_DELETE, dictService.buildDictValue(auto));
        rabbitTemplate.convertAndSend(ExchangeConst.OPC, RoutingKeyConst.OPC_COMMON,
                JsonUtil.toString(msg));
    }

    private void bulidBrandNameAndModelName(Auto auto) {
        auto.setAutoBrand(autoBrandService.getBrandNameById(auto.getAutoBrandId()));
        auto.setAutoModel(autoModelService.getModelNameById(auto.getAutoModelId()));
    }


}
